<template>
    <jb-crud-page
        ref="pageRef"
        title-icon="ic:round-manage-accounts"
        title-text="用户管理"
        search-url="/api/admin/user/datas"
        :search-conditions="searchForm"
        :edit-component="UserEdit"
        edit-modal-width="1000px"
    >
        <!-- 标题区域 -->
        <!-- 查询条件区域 start -->
        <template #conditions-form>
            <n-input
                v-model:value="searchForm.keywords"
                type="text"
                clearable
                class="w-140px"
                placeholder="输入关键字搜索"
                @keydown.enter="pageRef?.loadData(true)"
            />

            <jb-select
                v-model:value="searchForm.sex"
                url="/api/admin/dictionary/options?typeKey=sex"
                placeholder="=性别="
                class="w-130px"
            ></jb-select>

            <jb-select
                v-model:value="searchForm.ofModule"
                url="/api/admin/modules"
                placeholder="=选择模块="
                class="w-130px"
            ></jb-select>
            <jb-select
                v-model:value="searchForm.enable"
                url="/api/admin/dictionary/options?typeKey=options_enable"
                placeholder="=状态="
                class="w-130px"
            ></jb-select>
            <jb-tree-select
                v-model:value="searchForm.roleId"
                class="w-130px"
                url="/api/admin/role/options"
                check-strategy="child"
                placeholder="=角色="
            ></jb-tree-select>
            <jb-select
                v-if="config.postEnable"
                v-model:value="searchForm.postId"
                class="w-130px"
                url="/api/admin/post/options"
                placeholder="=岗位="
            ></jb-select>
        </template>
        <!-- 查询条件区域 end -->

        <!-- 操作按钮区域  -->
        <template #opt>
            <jb-btn
                :icon="Icons.ADD"
                ghost
                type="primary"
                @click="pageRef?.showEditModal('添加用户')"
                >新增</jb-btn
            >
        </template>

        <template #default="{ state }">
            <splitpanes class="h-full default-theme">
                <pane v-if="config.deptEnable" size="20">
                    <n-card
                        size="small"
                        class="h-full"
                        :segmented="{
                            content: true
                        }"
                        header-style="height:38px"
                    >
                        <template #header>
                            <div class="flex items-center">
                                <jb-icon
                                    icon="mingcute:department-fill"
                                    class="text-16px mr-8px inline-block shrink-0"
                                ></jb-icon>
                                <span class="shrink-0">部门：</span>
                                <span class="text-primary ellipsis-text">{{
                                    selectedDeptName
                                }}</span>
                            </div>
                        </template>
                        <template #header-extra>
                            <n-space justify="end" class="w-full">
                                <jb-btn
                                    :icon="Icons.REFRESH"
                                    quaternary
                                    circle
                                    tip-text="刷新部门数据"
                                    @click="loadDeptData()"
                                ></jb-btn>
                                <jb-btn
                                    :icon="Icons.REMOVE"
                                    tip-text="取消选中"
                                    type="error"
                                    quaternary
                                    circle
                                    @click="selectedDept = []"
                                ></jb-btn>
                            </n-space>
                        </template>
                        <div class="flex-1 flex-col overflow-auto">
                            <n-input
                                v-model:value="deptKeywords"
                                clearable
                                placeholder="关键字筛选"
                                class="shrink-0 mb-8px"
                            ></n-input>
                            <div class="flex-1">
                                <n-tree
                                    v-model:selected-keys="selectedDept"
                                    :pattern="deptKeywords"
                                    :show-irrelevant-nodes="false"
                                    :data="deptData"
                                    key-field="id"
                                    label-field="name"
                                    children-field="items"
                                    @update:selectedKeys="deptChange"
                                >
                                </n-tree>
                            </div>
                        </div>
                    </n-card>
                </pane>
                <pane size="80">
                    <jb-table
                        :row-config="{ height: 80 }"
                        :start-index="state.tableStartIndex"
                        :data="state.list"
                    >
                        <jb-column
                            type="seq"
                            title="序号"
                            width="60"
                            fixed="left"
                        ></jb-column>
                        <jb-column
                            field="name"
                            title="姓名"
                            min-width="140"
                            fixed="left"
                        ></jb-column>
                        <jb-column
                            field="username"
                            title="用户名"
                            min-width="140"
                        ></jb-column>
                        <jb-column field="avatar" title="头像" width="100">
                            <template #default="{ row }">
                                <jb-avatar :src="row.avatar"></jb-avatar>
                            </template>
                        </jb-column>
                        <jb-column field="sn" title="编号" width="120"></jb-column>
                        <jb-column field="sex" title="性别" width="60">
                            <template #default="{ row }">
                                <n-tag
                                    v-if="row.sex"
                                    :type="row.sex === 1 ? 'success' : 'warning'"
                                    >{{
                                        row?.sex === 1 ? '男' : row?.sex === 2 ? '女' : ''
                                    }}</n-tag
                                >
                            </template>
                        </jb-column>
                        <jb-column field="age" title="年龄" width="100"></jb-column>
                        <jb-column field="role" title="角色" min-width="140">
                            <template #default="{ row }">
                                <div v-if="row.userRoles?.length > 0" class="py-5px">
                                    <n-scrollbar style="max-height: 70px">
                                        <jb-tag-group
                                            size="small"
                                            :vertical="true"
                                            :tags="row.userRoles?.map((i: any) => i.name)"
                                        ></jb-tag-group>
                                    </n-scrollbar>
                                </div>
                                <span v-else>未设置</span>
                            </template>
                        </jb-column>

                        <jb-column
                            field="phone"
                            title="手机号"
                            min-width="140"
                        ></jb-column>

                        <jb-column field="email" title="E-mail" min-width="160">
                            <template #default="{ row }">
                                <span>{{ row?.email ? row?.email : '未设置' }}</span>
                            </template>
                        </jb-column>
                        <jb-column
                            field="isSystemAdmin"
                            title="是否为超管"
                            min-width="110"
                        >
                            <template #default="{ row }">
                                <n-tag
                                    :type="row.isSystemAdmin ? 'success' : 'default'"
                                    >{{
                                        row?.isSystemAdmin ? '超级管理员' : '一般用户'
                                    }}</n-tag
                                >
                            </template>
                        </jb-column>
                        <jb-column
                            field="enable"
                            title="是否启用"
                            width="80"
                            fixed="right"
                        >
                            <template #default="{ row }">
                                <jb-switch
                                    v-model:value="row.enable"
                                    :url="`/api/admin/user/toggleEnable/${row.id}`"
                                ></jb-switch>
                            </template>
                        </jb-column>
                        <jb-column title="操作" fixed="right" min-width="140">
                            <template #default="{ row }">
                                <jb-btn
                                    tip-text="编辑"
                                    :icon="Icons.EDIT"
                                    secondary
                                    circle
                                    type="primary"
                                    @click="
                                        pageRef?.showEditModal('编辑用户信息', {
                                            id: row.id
                                        })
                                    "
                                ></jb-btn>

                                <jb-btn
                                    confirm-text="确认删除该用户吗？"
                                    :url="`/api/admin/user/delete/${row.id}`"
                                    :icon="Icons.DELETE"
                                    tip-text="删除"
                                    secondary
                                    circle
                                    type="error"
                                    class="mx-8px"
                                    @success="pageRef?.loadData()"
                                >
                                </jb-btn>
                                <jb-btn
                                    tip-text="重置密码"
                                    secondary
                                    icon="solar:lock-password-bold"
                                    circle
                                    type="warning"
                                    :modal-component="ResetPwd"
                                    modal-title="重置密码"
                                    modal-width="600px"
                                    :modal-component-props="{ userId: row.id }"
                                    @modal-yes-click="doResetPwd"
                                >
                                </jb-btn>
                            </template>
                        </jb-column>
                    </jb-table>
                </pane>
            </splitpanes>
        </template>
    </jb-crud-page>
</template>

<script setup lang="ts">
import { onMounted, reactive, ref, watch } from 'vue'
import { Icons } from '@/constants'
import JbCrudPage from '@/components/_builtin/jb-crud-page/index.vue'
import { JBoltApi } from '@/utils/request'
import { useResetableData } from '@/hooks/common/use-resetable-data'
import { ResData } from '@/typings/request'

import { Model } from '@/typings/api'
import { DynamicComponentEmitArgs } from '@/typings/jbolt.components'
import JbTagGroup from '@/components/_builtin/jb-tag-group/index.vue'
import ResetPwd from './components/reset-pwd/index.vue'
import UserEdit from './components/user-edit/index.vue'

const pageRef = ref<InstanceType<typeof JbCrudPage> | null>(null)

/** 部门岗位相关配置 start */
const config = reactive({
    postEnable: false,
    deptEnable: false
})

async function loadConfig() {
    let res = await JBoltApi.tryGet<ResData>(
        '/api/admin/globalConfig/getByKeys?keys=SYSTEM_DEPT_ENABLE,SYSTEM_POST_ENABLE'
    )
    config.postEnable = res.data['SYSTEM_POST_ENABLE']
    config.deptEnable = res.data['SYSTEM_DEPT_ENABLE']
}
onMounted(() => {
    loadConfig()
})

/** 部门岗位相关配置 end */

/** table数据相关 start */
const searchForm = useResetableData({
    keywords: '',
    ofModule: '',
    sex: '',
    roleId: '',
    enable: '',
    postId: '',
    deptId: ''
})

/** table数据相关 end */

/** 部门树 start */
const deptKeywords = ref<string>('')
const deptData = ref<Model[]>([])
const selectedDept = ref<string[]>([])
const selectedDeptName = ref<string>('')
watch(
    () => selectedDept.value,
    (val) => {
        searchForm.deptId = val[0] ?? ''
        pageRef.value?.loadData(true)
        if (!val[0]) {
            selectedDeptName.value = ''
        }
    }
)
//监听点击重置按钮时，清空选中的部门
watch(
    () => searchForm.deptId,
    (newId) => {
        const deptId = selectedDept.value[0] ?? ''
        if (deptId != newId && !newId) {
            selectedDept.value = []
        }
    }
)
function deptChange(keys: any, option: any) {
    selectedDeptName.value = option[0]?.name ?? ''
}
function loadDeptData() {
    JBoltApi.tryGet('/api/admin/dept/enableOptions').then((res) => {
        deptData.value = res.data
    })
}
onMounted(() => {
    loadDeptData()
})
/** 部门树 end */

function doResetPwd({ close, componentRef }: DynamicComponentEmitArgs) {
    componentRef.submit().then(() => {
        close()
    })
}
</script>

<style></style>
